package com.ds.robot.assistant.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ds.robot.assistant.enums.Env;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Component
@Slf4j
@SuppressWarnings("all")
public class MessageSender {

    private final RestTemplate restTemplate;

    @Autowired
    public MessageSender(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    /**
     * 发送消息到企微
     *
     * @param message
     * @param env
     */
    public void sendMessage(String message, Env env) {
        if (Env.TEST.equals(env)) {
            log.info("当前为测试环境，不发送消息");
            return;
        }
        // 构建消息体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("msgtype", "markdown");
        Map<String, Object> markdown = new HashMap<>();
        markdown.put("content", message);
        markdown.put("mentioned_list", new String[]{"@all"});
        markdown.put("mentioned_mobile_list", new String[]{"@all"});
        requestBody.put("markdown", markdown);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            // 发送POST请求
            String webHookUrl = getWebHookUrl(env);
            ResponseEntity<String> response = restTemplate.postForEntity(webHookUrl, entity, String.class);

            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new RuntimeException("Failed to send message. HTTP status code: " + response.getStatusCode());
            }
            log.info("Message send successfully");
        } catch (Exception e) {
            log.error("Error sending message: " + e.getMessage());
        }
    }

    /**
     * 发送消息到企微并指定@用户ID列表
     *
     * @param message
     * @param env
     * @param idList
     */
    public void sendMessage(String message, Env env, List<String> idList) {
        // 构建消息体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("msgtype", "markdown");
        Map<String, Object> markdown = new HashMap<>();
        markdown.put("content", message);
        // markdown.put("mentioned_mobile_list", new String[]{"@all"});

        if (CollectionUtils.isEmpty(idList)) {
            markdown.put("mentioned_list", new String[]{"@all"});
        } else {
            String[] array = idList.toArray(new String[0]);
            markdown.put("mentioned_list", array);
        }
        requestBody.put("markdown", markdown);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            // 发送POST请求
            String webHookUrl = getWebHookUrl(env);
            ResponseEntity<String> response = restTemplate.postForEntity(webHookUrl, entity, String.class);

            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new RuntimeException("Failed to send message. HTTP status code: " + response.getStatusCode());
            }
            log.info("Message send successfully");
        } catch (Exception e) {
            log.error("Error sending message: " + e.getMessage());
        }
    }

    private String getWebHookUrl(Env env) {
        switch (env) {
            // 研发部群
            case PROD:
                return "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c9638350-8e39-4123-881e-0d0804a09720";
            // 产品群
            case PRODUCT_GROUP:
                return "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=9400fa1f-662f-44e3-90cc-5e409146f57b";
            // 数仓群
            case DATA_WAREHOUSE:
                return "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=67983313-a4b9-4cfc-b6c6-cc71c9779fb1";
            // 测试群
            case TEST:
            default:
                return "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=54b611ad-75a0-4e53-b84c-da3903833946";
        }
    }

    /**
     * 发送消息到企微
     *
     * @param message
     * @param env
     */
    public void sendPicMessage(String message, Env env) {
        // 构建消息体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("msgtype", "news");

        Map<String, Object> newsMap = new HashMap<>();
        Map<String, Object> articleMap = new HashMap<>();

        articleMap.put("title", "今日里程碑提醒");
        articleMap.put("description", "1.商城优惠券管理  [中午前]  发版上线 @魏韶颖 @马惠\n" +
                "2.商城优惠券的使用  [中午前]  发版上线 @魏韶颖 @马惠\n" +
                "3.商城优惠券管理  [中午前]  完成测试 @李梦倩\n");
        articleMap.put("url", "http://www.renruikeji.cn/");
        articleMap.put("picurl", "http://www.renruikeji.cn/upload/202207/1658828459.jpg");

        // 创建 articles 列表
        Map<String, Object>[] articlesArray = new Map[]{articleMap};
        newsMap.put("articles", articlesArray);
        requestBody.put("news", newsMap);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            // 发送POST请求
            String webHookUrl = getWebHookUrl(env);
            ResponseEntity<String> response = restTemplate.postForEntity(webHookUrl, entity, String.class);

            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new RuntimeException("Failed to send message. HTTP status code: " + response.getStatusCode());
            }
            log.info("Message send successfully");
        } catch (Exception e) {
            log.error("Error sending message: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        // List<String> idList = Arrays.asList("id1", "id2", "id3");
        //
        // // 不传递参数，但需要向下转型
        // String[] array1 = (String[]) idList.toArray();
        //
        // // 传递一个空的 String[] 数组作为参数
        // String[] array2 = idList.toArray(new String[0]);
        //
        // System.out.println(Arrays.toString(array1));
        // System.out.println(Arrays.toString(array2));
        //
        // String[] array = idList.stream().toArray(String[]::new);
        // System.out.println(Arrays.toString(array));

        try {
            // 创建 ObjectMapper 实例
            ObjectMapper mapper = new ObjectMapper();

            // 创建 HashMap 并填充数据
            Map<String, Object> rootMap = new HashMap<>();
            Map<String, Object> newsMap = new HashMap<>();
            Map<String, Object> articleMap = new HashMap<>();

            articleMap.put("title", "中秋节礼品领取");
            articleMap.put("description", "今年中秋节公司有豪礼相送");
            articleMap.put("url", "www.qq.com");
            articleMap.put("picurl", "http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png");

            // 创建 articles 列表
            Map<String, Object>[] articlesArray = new Map[]{articleMap};
            newsMap.put("articles", articlesArray);

            // 将 newsMap 添加到 rootMap
            rootMap.put("msgtype", "news");
            rootMap.put("news", newsMap);

            // 将 Map 转换为 JSON 字符串
            String jsonString = mapper.writeValueAsString(rootMap);

            // 输出 JSON 字符串
            System.out.println(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
